//
//  CountDownSelView.m
//  JPWords
//
//  Created by 梁淑婷 on 2024/6/29.
//

#import "CountDownSelView.h"

@interface CountDownSelView()<UIPickerViewDelegate, UIPickerViewDataSource,UITextFieldDelegate>

@property (nonatomic,strong)UITextField *nameTF;
@property (nonatomic, strong)UIPickerView *datePicker;
@property (nonatomic, strong)NSArray *years;
@property (nonatomic, strong)NSArray *months;
@property (nonatomic, strong)NSArray *days;
@property (nonatomic, strong)NSDateComponents *selectedDateComponents;
@property (nonatomic, assign)NSInteger selectedYearRow;
@property (nonatomic, assign)NSInteger selectedMonthRow;
@property (nonatomic, assign)NSInteger selectedDayRow;
@property(nonatomic,strong)UIView *bgView;
@property(nonatomic,strong)UIButton *cancelBtn;
@property(nonatomic,strong)UIButton *sureBtn;

@end

@implementation CountDownSelView

-(instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if(self){
        self.currentAvailableWidth = frame.size.width;
        self.currentAvailableHeight = frame.size.height;
        [self createUI];
    }
    return self;
}

-(void)createUI{
    
    self.backgroundColor = UIColorHex_(0x000000,0.4);
    
    CGFloat b_w = 316;
    CGFloat b_h = 324;
    if(self.currentAvailableWidth < 348){
        b_w = self.currentAvailableWidth-32;
    }
    __weak typeof(self)weakSelf = self;
    UIView *bgView = [[UIView alloc]init];
    bgView.backgroundColor = [UIColor whiteColor];
    bgView.layer.cornerRadius = 10;
    bgView.layer.masksToBounds = YES;
    [self addSubview:bgView];
    [bgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(b_w);
        make.height.mas_equalTo(b_h);
        make.centerY.mas_equalTo(weakSelf);
        make.centerX.mas_equalTo(weakSelf);
    }];
    self.bgView = bgView;
    
    self.nameTF = [[UITextField alloc]init];
    self.nameTF.font = JPUIFontPingFangBold(17);
    self.nameTF.textColor = KFontBlackColor;
    self.nameTF.tintColor = KThemeColor;
    self.nameTF.textAlignment = NSTextAlignmentCenter;
    self.nameTF.delegate = self;
    self.nameTF.text = @"JLPT倒计时";
    [bgView addSubview:self.nameTF];
    [self.nameTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(@16);
        make.right.mas_equalTo(@-16);
        make.height.mas_equalTo(@24);
        make.top.mas_equalTo(@20);
    }];
    
    // 初始化年月日数组
    [self initializeDateArrays];
       
    // 初始化UIPickerView
    self.datePicker = [[UIPickerView alloc] initWithFrame:CGRectMake(16, 64,b_w-32,b_h-64-76)];
    self.datePicker.delegate = self;
    self.datePicker.dataSource = self;
    [bgView addSubview:self.datePicker];
    
    // 初始化选中的日期为今天
    self.selectedDateComponents = [[NSCalendar currentCalendar] components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay) fromDate:[NSDate date]];
    
   
    
    UIButton *cancelBtn = [[UIButton alloc]init];
    [cancelBtn setTitle:@"取消" forState:UIControlStateNormal];
    [cancelBtn setTitleColor:KFontBlackColor forState:UIControlStateNormal];
    cancelBtn.titleLabel.font = JPUIFontPingFangSCRegular(16);
    [cancelBtn addTarget:self action:@selector(cancelBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [bgView addSubview:cancelBtn];
    [cancelBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.bottom.mas_equalTo(@0);
        make.height.mas_equalTo(@48);
        make.width.mas_equalTo(b_w/2.0);
    }];
    self.cancelBtn = cancelBtn;
    
    UIButton *sureBtn = [[UIButton alloc]init];
    [sureBtn setTitle:@"确定" forState:UIControlStateNormal];
    [sureBtn setTitleColor:KThemeColor forState:UIControlStateNormal];
    sureBtn.titleLabel.font = JPUIFontPingFangSCMedium(16);
    [sureBtn addTarget:self action:@selector(sureBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [bgView addSubview:sureBtn];
    [sureBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.bottom.mas_equalTo(@0);
        make.height.mas_equalTo(@48);
        make.width.mas_equalTo(b_w/2.0);
    }];
    self.sureBtn = sureBtn;
    
    UIView *line = [[UIView alloc]init];
    line.backgroundColor = KLineColor;
    [bgView addSubview:line];
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(@-48);
        make.height.mas_equalTo(@0.5);
        make.left.right.mas_equalTo(@0);
    }];
    
    UIView *line2 = [[UIView alloc]init];
    line2.backgroundColor = KLineColor;
    [bgView addSubview:line2];
    [line2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(@48);
        make.bottom.mas_equalTo(@0);
        make.width.mas_equalTo(@0.5);
        make.centerX.mas_equalTo(bgView);
    }];
    
    
}

-(void)refreshWidth{
    CGFloat b_w = 316;
    CGFloat b_h = 324;
    if(self.currentAvailableWidth < 348){
        b_w = self.currentAvailableWidth-32;
    }
    [self.bgView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(b_w);
        make.height.mas_equalTo(b_h);
    }];
    self.datePicker.frame = CGRectMake(16, 64,b_w-32,b_h-64-76);
    [self.datePicker reloadAllComponents];
    [self.cancelBtn mas_updateConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(b_w/2.0);
    }];
    [self.sureBtn mas_updateConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(b_w/2.0);
    }];
}


// 实现UITextFieldDelegate方法，限制输入长度为10个字符
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    // 当前输入框中的文本
    NSString *currentText = textField.text;
    // 替换后的文本
    NSString *updatedText = [currentText stringByReplacingCharactersInRange:range withString:string];

    // 判断替换后的文本长度是否超过10个字符
    return updatedText.length <= 10;
}


-(void)cancelBtnClick{
    [self removeFromSuperview];
}

-(void)sureBtnClick{
    if(self.nameTF.text.length == 0){
        [JPProgressHUD showMsg:@"请输入倒计时名称"];
        return;
    }
    NSString *selectedDate = [self getSelectedDate];
    if(selectedDate){
        BOOL isBefore = [self isDateBeforeToday:selectedDate];
        if(isBefore == YES){
            [JPProgressHUD showMsg:@"不能设置今天之前的时间"];
        }else{
            if(_sureBlock){
                _sureBlock(selectedDate,self.nameTF.text);
            }
        }
    }
}

#pragma mark - 对比选择的日期是不是在今天之前
- (BOOL)isDateBeforeToday:(NSString *)dateString {
    // 创建一个日期格式化器
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy年MM月dd日"];
    
    // 将传入的日期字符串转换为 NSDate 对象
    NSDate *inputDate = [dateFormatter dateFromString:dateString];
    if (!inputDate) {
        // 日期字符串无效
        return NO;
    }
    
    // 获取当前日期的开始时间（00:00:00）
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDate *today = [NSDate date];
    NSDateComponents *components = [calendar components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay) fromDate:today];
    NSDate *startOfToday = [calendar dateFromComponents:components];
    
    // 比较日期
    NSComparisonResult result = [inputDate compare:startOfToday];
    
    // 返回结果
    return (result == NSOrderedAscending);
}

- (NSString *)getSelectedDate {
    NSInteger selectedYearRow = [self.datePicker selectedRowInComponent:0];
    NSInteger selectedMonthRow = [self.datePicker selectedRowInComponent:1];
    NSInteger selectedDayRow = [self.datePicker selectedRowInComponent:2];

    NSString *selectedYearString = self.years[selectedYearRow];
    NSString *selectedYearNumberString = [selectedYearString substringToIndex:selectedYearString.length - 1];

    NSString *selectedMonthString = self.months[selectedMonthRow];
    NSString *selectedMonthNumberString = [selectedMonthString substringToIndex:selectedMonthString.length - 1];
    if (selectedMonthNumberString.length == 1) {
        selectedMonthNumberString = [NSString stringWithFormat:@"0%@", selectedMonthNumberString];
    }

    NSString *selectedDayString = self.days[selectedDayRow];
    NSString *selectedDayNumberString = [selectedDayString substringToIndex:selectedDayString.length - 1];
    if (selectedDayNumberString.length == 1) {
        selectedDayNumberString = [NSString stringWithFormat:@"0%@", selectedDayNumberString];
    }

    return [NSString stringWithFormat:@"%@年%@月%@日", selectedYearNumberString, selectedMonthNumberString, selectedDayNumberString];
}



- (void)initializeDateArrays {
    // 获取当前年份
    NSDateComponents *components = [[NSCalendar currentCalendar] components:NSCalendarUnitYear fromDate:[NSDate date]];
    NSInteger currentYear = [components year];
    
    // 初始化年份数组
    NSMutableArray *yearsArray = [NSMutableArray array];
    for (NSInteger year = currentYear; year <= currentYear + 10; year++) {
        [yearsArray addObject:[NSString stringWithFormat:@"%ld年", (long)year]];
    }
    self.years = yearsArray;
    
    // 初始化月份数组
    self.months = @[@"1月", @"2月", @"3月", @"4月", @"5月", @"6月", @"7月", @"8月", @"9月", @"10月", @"11月", @"12月"];
    
    // 初始化天数组
    [self updateDaysArrayForMonth:[components month] year:currentYear];
}

- (void)updateDaysArrayForMonth:(NSInteger)month year:(NSInteger)year {
    // 获取指定年月的天数
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
    [dateComponents setYear:year];
    [dateComponents setMonth:month];
    
    NSDate *date = [calendar dateFromComponents:dateComponents];
    NSRange daysRange = [calendar rangeOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitMonth forDate:date];
    
    NSMutableArray *daysArray = [NSMutableArray array];
    for (NSInteger day = 1; day <= daysRange.length; day++) {
        [daysArray addObject:[NSString stringWithFormat:@"%ld日", (long)day]];
    }
    self.days = daysArray;
    
    [self.datePicker reloadComponent:2];
}

#pragma mark - 选中今天
- (void)selectToday{
    NSDateComponents *components = [[NSCalendar currentCalendar] components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay) fromDate:[NSDate date]];
    
    NSInteger yearRow = [self.years indexOfObject:[NSString stringWithFormat:@"%ld年", (long)components.year]];
    NSInteger monthRow = components.month - 1;
    NSInteger dayRow = components.day - 1;
    
    self.selectedYearRow = yearRow;
    self.selectedMonthRow = monthRow;
    self.selectedDayRow = dayRow;
    
    [self.datePicker selectRow:yearRow inComponent:0 animated:NO];
    [self.datePicker selectRow:monthRow inComponent:1 animated:NO];
    [self.datePicker selectRow:dayRow inComponent:2 animated:NO];

    // 刷新所有组件，以便重新加载视图
    [self.datePicker reloadAllComponents];
}

#pragma mark - 选中日期
- (void)selectDateWithFormattedDate:(NSString *)formattedDate andName:(nonnull NSString *)name {
    self.nameTF.text = name;

    // 解析日期字符串
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy年MM月dd日"];
    NSDate *date = [dateFormatter dateFromString:formattedDate];
    if (!date) {
        [self selectToday];
    } else {
        NSDateComponents *components = [[NSCalendar currentCalendar] components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay) fromDate:date];
        
        NSInteger yearRow = [self.years indexOfObject:[NSString stringWithFormat:@"%ld年", (long)components.year]];
        NSInteger monthRow = components.month - 1;
        NSInteger dayRow = components.day - 1;
        
        // 检查 yearRow 是否在 years 数组范围内
        if (yearRow == NSNotFound || yearRow < 0 || yearRow >= self.years.count) {
            NSLog(@"无效的年份索引");
            yearRow = 0; // 设置一个默认的索引，例如 0
        }
        
        // 检查 monthRow 是否在有效范围内 (0 - 11)
        if (monthRow < 0 || monthRow >= 12) {
            NSLog(@"无效的月份索引");
            monthRow = 0; // 设置默认月份为 0
        }
        
        // 检查 dayRow 是否在有效范围内 (0 - 30)
        if (dayRow < 0 || dayRow >= 31) {
            NSLog(@"无效的日期索引");
            dayRow = 0; // 设置默认日期为 0
        }
        
        self.selectedYearRow = yearRow;
        self.selectedMonthRow = monthRow;
        self.selectedDayRow = dayRow;
        
        self.selectedDateComponents = components;
        
        [self.datePicker selectRow:yearRow inComponent:0 animated:NO];
        [self.datePicker selectRow:monthRow inComponent:1 animated:NO];
        [self.datePicker selectRow:dayRow inComponent:2 animated:NO];
        
        // 刷新所有组件，以便重新加载视图
        [self.datePicker reloadAllComponents];
    }
}




#pragma mark - UIPickerViewDataSource
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
    return 3;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    switch (component) {
        case 0:
            return self.years.count;
        case 1:
            return self.months.count;
        case 2:
            return self.days.count;
        default:
            return 0;
    }
}

#pragma mark - UIPickerViewDelegate

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view {
    for(UIView *singleLine in pickerView.subviews){
        singleLine.backgroundColor = [UIColor clearColor];
    }
    UILabel *pickerLabel = (UILabel *)view;
    if (!pickerLabel) {
        pickerLabel = [[UILabel alloc] init];
        pickerLabel.adjustsFontSizeToFitWidth = YES;
        pickerLabel.textAlignment = NSTextAlignmentCenter;
        pickerLabel.backgroundColor = [UIColor clearColor];
    }

    NSString *title = @"";
    switch (component) {
        case 0:
            title = self.years[row];
            break;
        case 1:
            title = self.months[row];
            break;
        case 2:
            title = self.days[row];
            break;
        default:
            break;
    }
    
    pickerLabel.text = title;

    if ((component == 0 && row == self.selectedYearRow) ||
        (component == 1 && row == self.selectedMonthRow) ||
        (component == 2 && row == self.selectedDayRow)) {
        pickerLabel.font = JPUIFontPingFangSCMedium(16); // 选中行字体大小
        pickerLabel.textColor = KFontBlackColor; // 选中行字体颜色
    } else {
        pickerLabel.font = JPUIFontPingFangSCRegular(16); // 未选中行字体大小
        pickerLabel.textColor = KFontGrayColor; // 未选中行字体颜色
    }

    return pickerLabel;
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
    switch (component) {
        case 0:{
            self.selectedYearRow = row;
            NSString *yearString = (NSString *)self.years[row];
            NSString *yearNumberString = [yearString substringToIndex:yearString.length - 1];
            self.selectedDateComponents.year = [yearNumberString integerValue];
        }
            break;
        case 1:{
            self.selectedMonthRow = row;
            self.selectedDateComponents.month = row + 1;
            [self updateDaysArrayForMonth:self.selectedDateComponents.month year:self.selectedDateComponents.year];
        }
            break;
        case 2:{
            self.selectedDayRow = row;
            self.selectedDateComponents.day = row + 1;
        }
            break;
    }

    // 刷新所有组件，以便重新加载视图
    [self.datePicker reloadAllComponents];
    
}

- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component {
    return 40.0; // 设置行高
}



@end
